<?php
class Manage extends MY_Controller
{
	public function __construct()
	{
		log_message('debug', '开始调用Role->Manage->__construct接口');
		parent::__construct();
		$this->loadLanguageFile('application/controllers/Role/');
		log_message('debug', '调用Role->Manage->__construct接口结束');
	}
	
	public function showView()
	{
		$this->load->view('module/Role/manage.htm');
	}
	
	public function post($url, $data)
	{
		$data = http_build_query($data);
		$opts = array (
			'http' => array (
			'method' => 'POST',
			'header'=> "Content-type:application/x-www-form-urlencoded",
			'content' => $data
			)
		);
		$context = stream_context_create($opts);
		return file_get_contents($url, false, $context);
	}
	
	public function getListData()
	{
		log_message('debug', '开始调用Role->Manage->getListData接口');
		$this->verifyPrivilege();
		
		try{
			$gameAreaId = $this->param->getParam('gameAreaId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$account = $this->param->getParam('account', array('method' => 'string', 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$roleName = $this->param->getParam('roleName', array(), 'post', true);
			$page = $this->param->getParam('page', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$rows = $this->param->getParam('rows', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$sort = $this->param->getParam('sort', array('method' => 'string', 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$order = $this->param->getParam('order', array('method' => 'string', 'emptyErrorCode' => 1, 'invalidErrorCode' => 1), 'post', true);
			$this->initGameAreaInfo($gameAreaId);
			if(empty($account))
			{
    			$sql = "select * from t_data_game_account where gameAreaId=$gameAreaId and roleName='$roleName'";
    			//error_log($sql);
    			$role = $this->gmDatabase->getRow($sql);
			    $account = $role['account'];
			}
			
			//error_log($gameAreaId.":".$account.":".$roleName);
			//error_log($this->ipAddress.":".$this->httpPort);
			
			$url = "http://".$this->ipAddress.":".$this->httpPort."/game/services?action=role&roleName=&account=".$account;
			//error_log($url);
			$result = file_get_contents($url);
// 			error_log("result = ".$result);
			$this->returnData['data']['total'] = 1;
			$temp = array();
			$jo = json_decode($result, true);
			$arr = array(
				'userId' => $jo['userId'],
				'roleId' => $jo['roleId'],
				'account' => $jo['account'],
				'roleName' => $jo['roleName'],
				'job' => $jo['job'],
				'sex' => $jo['sex'],
				'level' => $jo['level'],
				'vipLevel' => $jo['vipLevel'],
				'battleValue' => $jo['battleValue'],
				'token' => $jo['token'],
				'talkbanned' => $jo['talkbanned'],
				'enable' => $jo['enable']
			);

			$temp[] = $arr;
			$this->returnData['data']['rows'] = $temp;
		}
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
		
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
		
		$this->returnJson();
		log_message('debug', '调用Role->Manage->getListData接口结束');
	}
	
	public function kick() {
		log_message('debug', '=====开始调用Role->Manage->kick接口=====');
		$this->verifyPrivilege();
	
		try {
			$gameAreaId = $this->param->getParam('gameAreaId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$userId = $this->param->getParam('userId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$this->initGameAreaInfo($gameAreaId);
				
			if( $this->doKick($userId) === false ) {
				$this->setErrorCode(1);
			}
		}
	
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
	
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		$this->returnJson();
		log_message('debug', '=====调用Role->Manage->kick接口结束=====');
	}
	
	private function doKick($userId) {
		$sql = "
			select
				`usertoken`
			from
				`t_user`
			where
				`userId` = '{$userId}'
		";
		
		if( !(($row = $this->gameDatabase->getRow($sql)) === false) ) {
			$userToken = $row['usertoken'];
			$protocolCode = 61001;
			$host = $this->ipAddress;
			$port = ($this->portGroup-1)*100+60005;
			log_message('debug', "token:{$userToken}");
			log_message('debug', "host：{$host}");
			log_message('debug', "port：{$port}");
	
			$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
			if( socket_connect($socket, $host, $port) ) {
				log_message('debug', "开始发送61001协议");
				$message = '';
				
				$in = decbin($userId);
				$in = str_pad($in, 64, '0', STR_PAD_LEFT);
				$out = '';
				
				for ($i = 0, $len = strlen($in); $i < $len; $i += 8) {
					$out .= chr(bindec(substr($in,$i,8)));
				}
				$out = strrev($out);
				
				$message .= $out;
				$message .= pack('s', strlen($userToken));
				$message .= pack('a*', $userToken);		
				$encodeMessage = '';
				$parityByte = 0;
					
				for( $i=0 ; $i < strlen($message) ; $i++ ) {
					$tmpByte = ord(substr($message, $i, 1));
					$parityByte += $tmpByte;
					$tmpByte ^= 0x58;
					$tmpByte = substr(pack('n', $tmpByte), 1, 1);
					$encodeMessage .= $tmpByte;
				}
	
				$parityByte %= 99;
				$encodeMessage .= substr(pack('n', $parityByte), 1, 1);
				$head = substr(pack('n', 4), 1, 1);
				$head .= pack('S', $protocolCode);
				$head .= pack('l', strlen($encodeMessage)+7);
				$packageBin = $head.$encodeMessage;
	
				if(!socket_write($socket, $packageBin, strlen($packageBin))) {
					log_message('error', '发送数据失败');
					return false;
				}
	
				if( ($output = socket_read($socket, 1024)) !== false ) {
  					$resultUnpack = unpack('S', substr($output, 1, 2));
					log_message('debug', "返回协议号：{$resultUnpack[1]}");
						
					if($resultUnpack[1] != '61002') {
						log_message('error', '返回协议号错误');
						return false;
					}
				}
				else {
					log_message('error', '读取数据失败');
					return false;
				}
			}
			else {
				log_message('error', '连接端口失败');
				return false;
			}
		}
		else {
			log_message('error', '获取用户token失败');
			return false;
		}
	}
	
	function bannedRole() {
		log_message('debug', '=====开始调用Role->Manage->bannedRole接口=====');
		$this->verifyPrivilege();
	
		try {
			$gameAreaId = $this->param->getParam('gameAreaId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$userId = $this->param->getParam('userId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$bannedCycleType = $this->param->getParam('bannedCycleType', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1010001, 'invalidErrorCode' => 1));
			$bannedCycleValue = $this->param->getParam('bannedCycleValue', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1010002, 'invalidErrorCode' => 1010003));
			$reason = $this->param->getParam('reason', array('method' => 'string', 'emptyErrorCode' => 1010004, 'invalidErrorCode' => 1010005));
			$this->initGameAreaInfo($gameAreaId);
	
			$sql = "
				select
					count(*)
				from
					`t_user` a
				left join
					`t_char` b
				on
					a.`userid` = b.`uid`
				where
					a.`userid` = '{$userId}'
					and
					b.`enable` = '1'
			";
				
			if($this->gameDatabase->getColumn($sql) === '0') {
				$this->setErrorCode(1010006);
			}
			else {
				if( $this->doKick($userId) === false ) {
					$this->setErrorCode(1);
				}
				else {
					$sql = "
						update
							`t_user` a
						left join
							`t_char` b
						on
							a.`userid` = b.`uid`
						set
							b.`enable` = '0'
						where
							a.`userid` = '{$userId}'
					";
					$this->gameDatabase->query($sql);
	
					switch ($bannedCycleType) {
						case 1:
							$second = $bannedCycleValue * 60;
							break;
	
						case 2:
							$second = $bannedCycleValue * 3600;
							break;
	
						case 3:
							$second = $bannedCycleValue * 24 * 3600;
							break;
	
						case 4:
							$second = $bannedCycleValue * 30 * 24 * 3600;
							break;
	
						case 5:
							$second = $bannedCycleValue * 365 * 30 * 24 * 3600;
							break;
					}
	
					$sql = "
						insert into
							`t_log_banned_role`
						(
							`type`,
							`gameAreaId`,
							`userId`,
							`unbannedDateTime`,
							`status`,
							`operatorUserId`,
							`operatorDateTime`,
							`reason`
						)
						value
						(
							'1',
							'{$gameAreaId}',
							'{$userId}',
							from_unixtime(unix_timestamp(now()) + {$second}),
							'1',
							'{$this->currUserId}',
							now(),
							'{$reason}'
						)
					";
					$this->gmDatabase->query($sql);
				}
			}
		}
	
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
	
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		$this->returnJson();
		log_message('debug', '=====调用Role->Manage->bannedRole接口结束=====');
	}
	
	function unbannedRole() {
		log_message('debug', '=====开始调用Role->Manage->unbannedRole接口=====');
		$this->verifyPrivilege();
	
		try {
			$gameAreaId = $this->param->getParam('gameAreaId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$userId = $this->param->getParam('userId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$reason = $this->param->getParam('reason', array('method' => 'string', 'emptyErrorCode' => 1010004, 'invalidErrorCode' => 1010005));
			$this->initGameAreaInfo($gameAreaId);
			
			$sql = "
				select
					count(*)
				from
					`t_user` a
				left join
					`t_char` b
				on
					a.`userid` = b.`uid`
				where
					a.`userid` = '{$userId}'
					and
					b.`enable` = '0'
			";
				
			if($this->gameDatabase->getColumn($sql) === '0') {
				$this->setErrorCode(1010007);
			}
			else {
				$sql = "
					update
						`t_user` a
					left join
						`t_char` b
					on
						a.`userid` = b.`uid`
					set
						b.`enable` = '1'
					where
						a.`userid` = '{$userId}'
						and
						b.`enable` = '0'
				";
				$this->gameDatabase->query($sql);
				
				$sql = "
					insert into
						`t_log_banned_role`
					(
						`type`,
						`gameAreaId`,
						`userId`,
						`operatorUserId`,
						`operatorDateTime`,
						`reason`
					)
					value
					(
						'2',
						'{$gameAreaId}',
						'{$userId}',
						'{$this->currUserId}',
						now(),
						'{$reason}'
					)
				";
				$this->gmDatabase->query($sql);
			}
		}
	
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
	
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		$this->returnJson();
		log_message('debug', '=====调用Role->Manage->unbannedRole接口结束=====');
	}
	
	function bannedChat() {
		log_message('debug', '=====开始调用Role->Manage->bannedChat接口=====');
		$this->verifyPrivilege();
	
		try {
			$gameAreaId = $this->param->getParam('gameAreaId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$userId = $this->param->getParam('userId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$bannedCycleType = $this->param->getParam('bannedCycleType', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1010001, 'invalidErrorCode' => 1));
			$bannedCycleValue = $this->param->getParam('bannedCycleValue', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1010002, 'invalidErrorCode' => 1010003));
			$reason = $this->param->getParam('reason', array('method' => 'string', 'emptyErrorCode' => 1010004, 'invalidErrorCode' => 1010005));
			$this->initGameAreaInfo($gameAreaId);
	
			$sql = "
				select
					count(*)
				from
					`t_user` a
				left join
					`t_char` b
				on
					a.`userid` = b.`uid`
				where
					a.`userid` = '{$userId}'
					and
					b.`enable` = '1'
			";
	
			if($this->gameDatabase->getColumn($sql) === '0') {
				$this->setErrorCode(1010006);
			}
			else {
				$sql = "
					insert into
						`t_user_status`
					(
						`userid`,
						`talkbanned`
					)
					value
					(
						'{$userId}',
						'1'
					)
					on duplicate key update
						`talkbanned` = 1
				";
				$this->gameDatabase->query($sql);
					switch ($bannedCycleType) {
						case 1:
							$second = $bannedCycleValue * 60;
							break;
						
						case 2:
							$second = $bannedCycleValue * 3600;
							break;
						
						case 3:
							$second = $bannedCycleValue * 24 * 3600;
							break;
						
						case 4:
							$second = $bannedCycleValue * 30 * 24 * 3600;
							break;
						
						case 5:
							$second = $bannedCycleValue * 365 * 30 * 24 * 3600;
							break;
				}
	
				$sql = "
					insert into
						`t_log_banned_chat`
					(
						`type`,
						`gameAreaId`,
						`userId`,
						`unbannedDateTime`,
							`status`,
						`operatorUserId`,
						`operatorDateTime`,
						`reason`
					)
					value
					(
						'1',
						'{$gameAreaId}',
						'{$userId}',
						from_unixtime(unix_timestamp(now()) + {$second}),
						'1',
						'{$this->currUserId}',
						now(),
							'{$reason}'
					)
				";
				$this->gmDatabase->query($sql);
			}
		}
	
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		catch(MY_Mysql_Exception $e) {
			$this->setErrorCode(1);
		}
	
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		$this->returnJson();
		log_message('debug', '=====调用Role->Manage->bannedChat接口结束=====');
	}
	
	function unbannedChat() {
		log_message('debug', '=====开始调用Role->Manage->unbannedChat接口=====');
		$this->verifyPrivilege();
	
		try {
			$gameAreaId = $this->param->getParam('gameAreaId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 201, 'invalidErrorCode' => 1));
			$userId = $this->param->getParam('userId', array('method' => 'int', 'min' => 1, 'emptyErrorCode' => 1, 'invalidErrorCode' => 1));
			$reason = $this->param->getParam('reason', array('method' => 'string', 'emptyErrorCode' => 1010004, 'invalidErrorCode' => 1010005));
			$this->initGameAreaInfo($gameAreaId);
				
			$sql = "
				select
					count(*)
				from
					`t_user_status`
				where
					`userid` = '{$userId}'
					and
					`talkbanned` = '1'
			";
	
			if($this->gameDatabase->getColumn($sql) === '0') {
				$this->setErrorCode(1010007);
			}
			else {
				$sql = "
					update
						`t_user_status`
					set
						`talkbanned` = 0
					where
						`userId` = '{$userId}'
				";
				$this->gameDatabase->query($sql);
	
				$sql = "
					insert into
						`t_log_banned_chat`
					(
						`type`,
						`gameAreaId`,
						`userId`,
						`operatorUserId`,
						`operatorDateTime`,
						`reason`
					)
					value
					(
						'2',
						'{$gameAreaId}',
						'{$userId}',
						'{$this->currUserId}',
						now(),
						'{$reason}'
					)
				";
				$this->gmDatabase->query($sql);
			}
		}
	
		catch(MY_Param_Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
			catch(MY_Mysql_Exception $e) {
		$this->setErrorCode(1);
		}
	
		catch(Exception $e) {
			$this->setErrorCode($e->getCode());
		}
	
		$this->returnJson();
		log_message('debug', '=====调用Role->Manage->unbannedChat接口结束=====');
	}
}